import { createWebHashHistory, createRouter } from 'vue-router'
import {useUserStore} from '@/store/user'

const routes = [
  { 
    path: '/', 
    name: 'home',
    redirect:'/articles',
    meta:{
      requireAuth: true
    },
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path:'/articles',
        name:'文章管理',
        meta:{
          requireAuth: true
        },
        redirect:'/articles/all_article',
        children:[
          {
            path: '/articles/all_article',
            name:'全部文章',
            meta:{
              requireAuth: true
            },
            component:()=>import('@/views/articles/AllArticles.vue')
          },
          {
            path: '/articles/my_article',
            name:'我的文章',
            meta:{
              requireAuth: true
            },
            component:()=>import('@/views/articles/MyArticles.vue')
          }
        ]
      },
      {
        path:'/goods',
        name:'商品管理',
        meta:{
          requireAuth: true
        },
        redirect:'/goods/all_goods',
        children:[
          {
            path: '/goods/all_goods',
            name:'全部商品',
            meta:{
              requireAuth: true
            },
            component:()=>import('@/views/goods/AllGoods.vue')
          },
          {
            path: '/goods/my_goods',
            name:'我的商品',
            meta:{
              requireAuth: true
            },
            component:()=>import('@/views/goods/MyGoods.vue')
          }
        ]
      }
      ,
      {
        path:'/personal',
        name:'个人设置',
        meta:{
          requireAuth: true
        },
        redirect:'/personal/myinfo',
        children:[
          {
            path: '/personal/myinfo',
            name:'个人信息',
            meta:{
              requireAuth: true
            },
            component:()=>import('@/views/personal/index.vue')
          }
        ]
      }
    ]
  },
  { 
    path: '/register', 
    name: 'register',
    meta:{
      requireAuth: false
    },
    component: () => import('@/views/register/index.vue')  
  }
  ,
  { 
    path: '/login', 
    name: 'login',
    meta:{
      requireAuth: false
    },
    component: () => import('@/views/login/index.vue')  
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach((to)=>{
  const userStore = useUserStore()
  const { isLogined } = userStore
  if(to.meta.requireAuth === true && !isLogined){
    return {
      name:'login'
    }
  }
})

export default router

